package repository

import (
	"context"
	"gin/webook/internal/domain"
	"gin/webook/internal/repository/dao"
	"gin/webook/internal/web/validate"
	"time"
)

var (
	ErrDuplicateEmail = dao.ErrDuplicateEmail
	ErrUserNotFound   = dao.ErrRecordNotFound
)

type UserRepository struct {
	dao *dao.UserDao
}

func NewUserRepository(dao *dao.UserDao) *UserRepository {
	return &UserRepository{dao: dao}
}

func (repo *UserRepository) Create(ctx context.Context, u domain.User) error {
	err := repo.dao.Insert(ctx, dao.User{
		Email:      u.Email,
		Password:   u.Password,
		CreateTime: 0,
		UpdateTime: 0,
	})
	if err == dao.ErrDuplicateEmail {
		return ErrDuplicateEmail
	}
	return err
}

func (repo *UserRepository) FindByEmail(ctx context.Context, email string) (domain.User, error) {
	u, err := repo.dao.FindByEmail(ctx, email)
	if err != nil {
		return domain.User{}, err
	}
	return repo.toDomain(u), nil
}

func (repo *UserRepository) FindByUid(ctx context.Context, uid int64) (domain.User, error) {
	u, err := repo.dao.FindByUid(ctx, uid)
	if err != nil {
		return domain.User{}, err
	}
	return repo.toDomain(u), nil
}

func (repo *UserRepository) toDomain(u dao.User) domain.User {
	birth := time.Unix(u.Birth, 0).Format("2006-01-02 15:04:05")
	return domain.User{
		Id:           u.Id,
		Email:        u.Email,
		Password:     u.Password,
		NickName:     u.NickName,
		Birth:        birth,
		Introduction: u.Introduction,
	}
}

func (repo *UserRepository) UpdateUserInfoByUid(ctx context.Context, uid int64, req validate.ProfileReq) (domain.User, error) {
	u, err := repo.dao.UpdateUserInfoByUid(ctx, uid, req)
	if err != nil {
		return domain.User{}, err
	}
	return repo.toDomain(u), nil
}
